import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
import wtdatas from '../../model/data/weightdata';
import { cloneDeep } from '../../utils/util'
import bleUtils from '../../utils/bluetooth'


//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		showDialogdevice: false,
		inputshow: false,
		//unit  为展示的名称，code是给刘哥传入的参数（不是展示名称对应的code），rawdata是获取接口的参数名
		inputlist: [
			{ unit: '体重kg', value: '', text: '请输入体重', code: 'XYZBXY001007', rawdata: 'weight_kg' },
			{ unit: 'BMI', value: '', text: '请输入bmi', code: 'XYZBXY001001', rawdata: 'bmi' },
			{ unit: '体脂率', value: '', text: '请输入体脂率', code: 'lk1590141731679', rawdata: 'bfp' },
			{ unit: '肌肉量', value: '', text: '请输入肌肉量', code: 'HXJK00000009', rawdata: 'muscle' },
			{ unit: '基础代谢', value: '', text: '请输入基础代谢', code: 'lk1590141731918', rawdata: 'bmr' },
			{ unit: '身体年龄', value: '', text: '请输入身体年龄', code: 'HXJK00000003', rawdata: 'age' },
			{ unit: '内脏脂肪等级', value: '', text: '请输入内脏脂肪等级', code: 'XYZBXY001035', rawdata: 'vfal' },
			{ unit: '肌肉率', value: '', text: '请输入肌肉率', code: 'XYZBXY001032', rawdata: 'muscle' },
			{ unit: '水分率', value: '', text: '请输入水分率', code: 'XYZBXY001029', rawdata: 'water' },
			{ unit: '蛋白质率', value: '', text: '请输入蛋白质率', code: 'lk1636612991835', rawdata: 'protein' },
			{ unit: '骨骼肌', value: '', text: '请输入骨骼肌', code: 'HXJK00000002', rawdata: 'sm' },
			{ unit: '肌肉控制', value: '', text: '请输入肌肉控制', code: 'HXJK00000012', rawdata: 'muscle_control' },
			{ unit: '脂肪控制', value: '', text: '请输入脂肪控制', code: 'HXJK00000013', rawdata: 'bfm_control' },
			{ unit: '肥胖等级', value: '', text: '请输入肥胖等级', code: 'HXJK00000007', rawdata: 'bmi' },
			{ unit: '体型', value: '', text: '请输入体型', code: 'HXJK00000014', rawdata: 'body_type' },
		],
		iconlist: [
			{ name: '体重',  code: 'XYZBXY001007', img: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/weightManagement/icon_BMI.png' },
			{ name: 'BMI', toFixedNum: 1,  unit: '', bg:['#f62c12','#3fc500','#f62c12','#f62c12'], code: 'XYZBXY001001', img: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/weightManagement/icon_BMI.png' },
			{ name: '体脂率', toFixedNum: 1,  unit: '%', bg:['#3fc500','#3fc500','#f62c12','#f62c12'], code: 'lk1590141731679', img: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/weightManagement/icon_tzl.png' },
			{ name: '肌肉',toFixedNum: 1,  unit: 'kg', bg:['#f62c12','#3fc500','#f62c12'], code: 'HXJK00000009', img: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/weightManagement/icon_jrls.png' }
		],
		dataList: [],
		c_val: 80,
		shebeiicon: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/weightManagement/icon_tizhicheng.png',
		shebeiicon_r: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/weightManagement/icon_clls.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		weightValueLast: '--',
		bmiValueLast: '--',
		bodyFaValueLast: '--',
		moistureValueLast: '--',
		muscleValueLast: '--',
		bmrValueLast: '--',
		boneValueLast: '--',
		linedata: null,
		editWvalue: '',
		show: false,
		ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
		},
		weightValue: '--',
		bmiValue: '--',
		bodyFaValue: '--',
		moistureValue: '--',
		muscleValue: '--',
		bmrValue: '--',
		boneValue: '--',
		datas: null,
		showDialog: false,
		bindDeviceTextInfo: '',
		hasSave: false,
		height: '',
		gender: '',
		age: 0,
		searchDevice: [],
		bindDevice: {},
		bleStatus: true,
		isInit: false,
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onShow(options) {
		// const { titlename } = options
		// // this.doInitBlue()
		// console.log(titlename);
		wx.setNavigationBarTitle({
			title: '体脂监测' // 设置页面标题
		})
		// this.drawProgress()
		const userInfo = wx.getStorageSync('userInfo')
		if(!userInfo.birthday) { // 如果没有生日
			wx.showToast({
				icon: 'none',
				title: '请完善生日信息'
			});
			wx.navigateTo({
				url: `/pages/login/birthday`
			})
			return
		}
		if (!userInfo.gender) {
			wx.showToast({
				icon: 'none',
				title: '请完善性别信息'
			});
			wx.navigateTo({
				url: `/pages/login/sex`
			})
			return
		}
		if (!userInfo.height) {
			wx.showToast({
				icon: 'none',
				title: '请完善身高信息'
			});
			wx.navigateTo({
				url: `/pages/login/height`
			})
			return
		}
		this.setData({
			height: userInfo.height,
			gender: userInfo.gender,
			age: this.calculateAge(userInfo.birthday)
		})
		this.gethistrorylist(true); //查看历史数据
		// this.getloadlist(true); // 查询最新数据
		this.setData({
			isInit: false
		})
		this.doInitBlue()
		// setTimeout(() => {
		// }, 1000)
	},
	onDevice() {
		this.onShow()
	},
	initPlu() {

		var icommon = requirePlugin('ICDeviceManager');
		this.icommon = icommon;
		this.ICDeviceManager = new icommon.ICDeviceManager();
		this.ICDeviceManager.init((isInit) => {
			console.log(isInit, 'isInit')
			this.setData({
				isInit: true
			})
			// const isV = this.ICDeviceManager.ICConstant.ICBleState
			this.ICDeviceManager.setDelegate({
				onReceiveWeightData: (device, model) => {
					wtdatas.weightImport(model);
					console.log(model, '秤收到的数据');
					// 在收到数据的同时，实时变化页面上的值
					let text1 = ''
					let wtinfo = wtdatas['weight_info']
					for (let wt in wtinfo) {
						text1 = text1 + wt + '：' + wtinfo[wt] + '\n'
					}

					this.setData({
						datas: text1
					})

					if (this.delayer) {
						clearTimeout(this.delayer)
						this.delayer = null
					}

					this.delayer = setTimeout(async () => {
						const { isStabilized } = model
						const { datas } = this.data
						const dataObject = {}
						console.log(datas, 'datas')
						datas.split(/\n/).forEach(function (line) {
							// 将行分割为键和值
							const parts = line.split(/：/)
							const key = parts[0]
							const value = parts[1]
							// 将键和值添加到对象中
							dataObject[key] = value
						})

						if (isStabilized) {
							if(this.data.hasSave) {
								return
							}
							this.setData({
								hasSave: true
							})
							// 调用数据保存的接口
							const dataFarmatter = data => {
								if (!data) {
									return ''
								}
								if (data === '' || data == 0) {
									return ''
								}
								return data
							}
							// 处理页面上的字符串数据
							const {
								weight_kg: weight,
								smPercent,
								bmi,
								bfr, //体脂率
								sfr, //皮下脂肪
								uvi, //内脏脂肪指数
								musclePercent, //肌肉率
								bmr, //基础代谢率
								bm, //骨重
								vwc, //水含量
								body_age, //身体年龄
								pp //蛋白率
							} = dataObject
							const data = {
								weight,
								bmi,
								// mac: wx.getStorageSync(LOCAL.HXEQUCODE), //设备 mac 地址
								bfr: dataFarmatter(bfr), //体脂率
								sfr: dataFarmatter(sfr), //皮下脂肪
								uvi: dataFarmatter(uvi), //内脏脂肪指数
								musclePercent: dataFarmatter(musclePercent), //肌肉率
								bmr: dataFarmatter(bmr), //基础代谢率
								bm: dataFarmatter(bm), //骨重
								vwc: dataFarmatter(vwc), //水含量
								body_age: dataFarmatter(body_age)
									? Number(dataFarmatter(body_age)).toFixed(2)
									: '', //身体年龄
								pp: dataFarmatter(pp), //蛋白率
								smPercent: dataFarmatter(smPercent) //骨骼肌率
							}
							this.getAlgorithmsAalc(weight, model.impendences)
							console.log(data, '接口入参数据')
							// await this.saveData(data)
							// await this.getData()
						}
					}, 500)
				}
			});
		});
	},
	// 蓝牙初始化
  doInitBlue() {
    bleUtils.initBlueTooth().then((res) => {
			this.setData({
				bleStatus: true,
			})
			this.initPlu()
			this.doBluetoothAdapterStateChange()
			this.get()
    }).catch(error => {
			this.doBluetoothAdapterStateChange()
			this.setData({
				bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
			})
			this.setData({
				bleStatus: false,
				showDialog: true
			})
			// this.get()
		})
  },
	async get() {
		try {
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'bodyfat')
				if(listValue.length > 0 && listValue[0].devicelist.length > 0 && this.data.bleStatus) {
					this.addDevice(listValue[0].devicelist[0])
				} else {
					console.log('没有设备------------------');
					this.setData({
						showDialogdevice: true
					})
				}
		  } else {
			console.log('没有设备------------------');
			this.setData({
				showDialogdevice: true
			})
		}
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
	calculateAge(birthday) {
		const currentDate = new Date();
		const birthDate = new Date(birthday);

		let age = currentDate.getFullYear() - birthDate.getFullYear();

		// 检查当前月份和日期是否已过生日
		if (currentDate.getMonth() < birthDate.getMonth() || (currentDate.getMonth() === birthDate.getMonth() && currentDate.getDate() < birthDate.getDate())) {
			age--;
		}
		return age;
	},
	// 停止扫描
	stopScan() {
		this.ICDeviceManager.stopScan();
	},
	// 搜索设备
	scanDeviceIC() {
		console.log('开始搜索设备')
		// 如果设备是已知mac地址的，可以直接addDevice,无需去扫描，插件内部会自己做扫描
		this.ICDeviceManager.scanDevice((model) => {
			if (model && model.name === 'HXJK') {
				console.log(model, 'modelmodelmodel')
				// 找到设备后，停止扫描。调用scanDevice后，需开发者自己调用stopScan才会停止扫描，否则将会一直扫描，特例：蓝牙关闭后也会自己停止扫描
				this.setData({
					searchDevice:[model]
				})
				this.stopScan();
				// 添加回调成功不代表连接成功，这里只是说明设备已经添加到插 件了，连接状态看onDeviceConnectionChanged
				// this.ICDeviceManager.addDevice(model.macAddr, (macAddr, code) => {
				// 	console.log('添加设备成功code=' + code);
				// 	this.setData({
				// 		bindDeviceTextInfo: '正在测量中'
				// 	})
				// });
			}
		});
	},
	getSearchDevice() {
		return this.data.searchDevice
	},
	addDevice(model) {
		console.log(model, 'modelmodelmodelmodel')
		this.setData({
			hasSave: false,
			bindDevice:model,
			bindDeviceTextInfo: '正在连接蓝牙设备'
		})
		this.setData({
			showDialog: true
		})
		this.ICDeviceManager.addDevice(model.deviceId ? model.deviceId : model.macAddr, (macAddr, code) => {
			console.log('添加设备成功code=' + code);
			this.setData({
				bindDeviceTextInfo: '正在测量中'
			})
		});
	},
	// 数据详情
	getLoadDesc(id, isFirst) {
		api
			.post(`/api/exams/record/${id}`, {
				data: {
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----xiangq----', res);
				if (res[0].devices[0].items.length > 0) {
					console.log(res[0].devices[0].items);
					let items = res[0].devices[0].items
					const updatedItems = items.map(item => {
						return {
							...item,
							appendix: item.appendix?JSON.parse(item.appendix):''
						};
					});
					this.setData({
						weightlist: updatedItems[0]
					});
					let addlistAll = []
					if(updatedItems.length === 1 && updatedItems[0].code === 'XYZBXY001007') {
						 addlistAll = [
							{
								"normal": "true",
								"code": "XYZBXY001001",
								"maxvalue": "23.90",
								"appendix": {
									advice: "标准型建议：↵请继续保持，搭配合适的运动以增强自身体质。",
									levels:  ["偏低", "标准", "偏高", "高"],
									ticks:  ["18.5", "24.0", "28.0"],
									description: '',
								},
								"causedesc": "",
								"normvalue": "",
								"scale": "2",
								"type": "NUMBER",
								"minvalue": "18.90",
								"unit": "kg/m^2",
								"name": "BMI",
								"options": "[]",
								"value": "--",
								"desc": "目前常用的体重指数， 简称 BMI，又译为体质指数，是国际上常用的衡量人体肥胖程度和是否健康的重要标准。计算方法：BMI=体重/身高的平方。"
							}, {
								"normal": "true",
								"code": "lk1590141731679",
								"maxvalue": "",
								"appendix": {
									advice: "标准型建议：↵请继续保持，搭配合适的运动以增强自身体质。",
									levels:  ["偏低（优）", "标准", "偏高", "高"],
									ticks:  ["18", "26", "29"],
									description: '',
								},
								"causedesc": "",
								"normvalue": "",
								"scale": "",
								"type": "NUMBER",
								"minvalue": "",
								"unit": "",
								"name": "体脂率",
								"options": "[]",
								"value": "--",
								"desc": ""
							},
							{
								"normal": "true",
								"code": "HXJK00000009",
								"maxvalue": "",
								"appendix": {
									advice: "标准型建议：↵请继续保持，搭配合适的运动以增强自身体质。",
									levels: ["偏低", "正常", "优"],
									ticks: ["55", "69"],
									description: '',
								},
								"causedesc": "",
								"normvalue": "",
								"scale": "1",
								"type": "NUMBER",
								"minvalue": "",
								"unit": "kg",
								"name": "肌肉",
								"options": "",
								"value": "--",
								"desc": ""
							}
						]
					}
					if(updatedItems.length > 1) {
						const findData = updatedItems.find(item => item.code === 'lk1590141731679')
						if(!findData) {
							addlistAll.push({
								"normal": "true",
								"code": "lk1590141731679",
								"maxvalue": "",
								"appendix": {
									advice: "标准型建议：↵请继续保持，搭配合适的运动以增强自身体质。",
									levels:  ["偏低（优）", "标准", "偏高", "高"],
									ticks:  ["18", "26", "29"],
									description: '',
								},
								"causedesc": "",
								"normvalue": "",
								"scale": "",
								"type": "NUMBER",
								"minvalue": "",
								"unit": "",
								"name": "体脂率",
								"options": "[]",
								"value": "--",
								"desc": ""
							})
						}
						const findData1 = updatedItems.find(item => item.code === 'HXJK00000009')
						if(!findData1) {
							addlistAll.push({
								"normal": "true",
								"code": "HXJK00000009",
								"maxvalue": "",
								"appendix": {
									advice: "标准型建议：↵请继续保持，搭配合适的运动以增强自身体质。",
									levels: ["偏低", "正常", "优"],
									ticks: ["55", "69"],
									description: '',
								},
								"causedesc": "",
								"normvalue": "",
								"scale": "1",
								"type": "NUMBER",
								"minvalue": "",
								"unit": "kg",
								"name": "肌肉",
								"options": "",
								"value": "--",
								"desc": ""
							})
						}
					}
					this.getdataList(updatedItems.concat(addlistAll))
					if(!isFirst) {
						// this.goDetails()
					}
				}
			});
	},
	sortByCode(dataArray, orderArray) {
    // 创建一个对象映射，将code与对应的数据对象建立关系
    const codeMap = {};
    dataArray.forEach(data => {
      codeMap[data.code] = data;
    });

    // 根据给定数组的顺序对数据进行排序
    const sortedArray = orderArray.map(code => codeMap[code]);
		console.log(sortedArray);
    return sortedArray;
  },
	// 数据格式
	getdataList(items) {
	console.log(items,'items');

		let iconlist = this.data.iconlist
	console.log(iconlist,'iconlist');

		const sortKeyList = [
      'XYZBXY001007', 'XYZBXY001001', 'lk1590141731679', 'HXJK00000009', 'HXJK00000006', 'lk1590141731918', 'HXJK00000003',
      'XYZBXY001035', 'XYZBXY001032', 'XYZBXY001029', 'lk1636612991835','HXJK00000002','HXJK00000012','HXJK00000013','HXJK00000008','HXJK00000007',
    ]
	const sortItemsList = this.sortByCode(items, sortKeyList)
	console.log(sortItemsList, 'sortItemsList');
    if(!sortItemsList) {
      return
    }
		const list = []
    // 过滤并添加items中的属性到iconlist对应的项目中
    sortItemsList.forEach(item => {
      if(item && item.code) {
        const matchingItem = iconlist.find(iconItem => item.code === iconItem.code)
        if (matchingItem) {
          const obj = item
          if(matchingItem.toFixedNum && item.value !== '--') {
            obj.value = parseFloat(item.value).toFixed(1)
          }
          obj.level = item.appendix.level
          obj.ticks = item.appendix.ticks
          obj.levels = item.appendix.levels
          obj.description = item.appendix.description
          obj.advice = item.appendix.advice
          obj.img = matchingItem.img
          obj.bg = matchingItem.bg
          obj.unit = matchingItem.unit
          obj.name = matchingItem.name
          list.push(obj)
        }
      }
    })
		for (let j = 0; j < list.length; j++) {
      console.log(list[j]);
			if(list[j].levels) {
				let array = list[j].levels
				for (let y = 0; y < array.length; y++) {
					if(list[j].level == array[y])
					list[j].ids = y
				}
			}
    }
		console.log(list,'dsdf')
		const bmid = list.find(i => i.code === 'XYZBXY001001')
		console.log(bmid,'bmid')
		if (!bmid) {
			list.splice(1, 0, {
				name: 'BMI',
				value: '--',
				code: 'XYZBXY001001',
				unit: ''
			});
		}
    // 输出处理后的updatedIconlist数组
    this.setData({
      dataList: list
    });
	},
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		this.ICDeviceManager.stopScan();
	},
	getWeekDays() {
		let dates = []
		for (var i = 365; i >= 0; i--) {
			var currentDate = new Date();
			currentDate.setDate(currentDate.getDate() - i);
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var formattedDate = month + "/" + day;
			dates.push(formattedDate);
		}
		return dates
	},
	gethistrorylist(isFirst = true) {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					everyday: true,
					itemcode: 'XYZBXY001007',
					typecode: 'hxfatmeter',
					everyday: true
				},
				head: {
					firstresult: 0,
					maxresults: 1000,
					bodytype: 'flat',
				}
			})
			.then((res) => {
				console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001007" 的项
							const item = device.items.find((item) => item.code === 'XYZBXY001007');

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item) {
								console.log(item);
								values.push(Number(item.value)); // 将值转换为数字类型
								times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
							}
						});
					});
					const linedata = {
						values,
						times
					};
					console.log(linedata);
					this.setData({
						linedata,
						examid: res[res.length - 1].id
					});
					this.getLoadDesc(res[res.length - 1].id, isFirst)
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				} else {
					const linedata = {
						values: [],
						times: this.getWeekDays()
					};
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});
	},
	goHistory() {
		wx.navigateTo({ url: '/weightManagement/pages/history/index' });
	},
	getBodyTypeStr(type) {
		switch (type) {
			case 0:
				return '消廋型';
			case 1:
				return '偏瘦型';
			case 2:
				return '肌肉苗条型';
			case 3:
				return '苗条型';
			case 4:
				return '肌肉型';
			case 5:
				return '匀称型';
			case 6:
				return '运动员';
			case 7:
				return '略显肥胖型';
			case 8:
				return '肥胖型';
			case 9:
				return '偏胖型';
			case 10:
				return '隐形肥胖型';
		}
	},
	// 请求沃莱体脂算法接口
	getAlgorithmsAalc(weight, impendences) {
		wx.request({
			url: 'https://open.fitdays.cn/api/algorithms/calc',
			method: 'POST',
			data: {
				secret: '0566d14871021000',
				alg_type: 19,
				height: this.data.height,
				weight,
				age: this.data.age,
				sex: this.data.gender,
				people_type: 0,
				impendances: impendences
			},
			success: (res) => {
			  console.log(res, 'AAA');
				const value = res.data.data
			  console.log(value, 'BBBB');
				// 测量完成
				const list = cloneDeep(this.data.inputlist)
				list.forEach(item => {
					if(item.code === 'XYZBXY001007') {
						item.value = weight || '--'
					} else if (item.code === 'HXJK00000014') {
						item.value = this.getBodyTypeStr(value[item.rawdata]) || '--'
					} else{
						item.value = value[item.rawdata] || '--'
					}
				})
				this.setData({
					inputlist: list,
				});
				// this.setData({
				// 	'inputlist[2].value': data.bfr || '--',
				// });
				// this.setData({
				// 	'inputlist[3].value': data.sfr || '--',
				// });
				// this.setData({
				// 	'inputlist[4].value': data.uvi || '--',
				// });
				// this.setData({
				// 	'inputlist[5].value': data.musclePercent || '--',
				// });
				// this.setData({
				// 	'inputlist[6].value': data.bmr || '--',
				// });
				// this.setData({
				// 	'inputlist[7].value': data.bm || '--',
				// });
				// this.setData({
				// 	'inputlist[8].value': data.vwc || '--',
				// });
				// this.setData({
				// 	'inputlist[9].value': data.body_age || '--',
				// });
				// this.setData({
				// 	'inputlist[10].value': data.pp || '--',
				// });
				// this.setData({
				// 	'inputlist[11].value': data.smPercent || '--'
				// });
				console.log(this.data.inputlist, 'inputlist');
				console.log(list, 'list')
				this.savedevices(2);
				this.setData({
					bindDeviceTextInfo: '测量完成'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false,
					})
				}, 500);
				this.delayer = null
			},
			fail:(error) => {
			  console.log(error);
			}
		});
	},
	getloadlist(isFirst = true) {
		// 查询最新数据
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'hxfatmeter',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----最新数据----', res);
				const array = res;
				this.setData({
					newtime: res[0].examtime,
					examid: res[0].examid
				});
				this.getLoadDesc(res[0].examid, isFirst)
			});
	},
	// if(item.code == 'XYZBXY001007') {
	// 	if(item.value == '0' || item.value == '' || item.value == '0.0') {
	// 		console.log('1111');
	// 		wx.showToast({
	// 			icon: 'none',
	// 			title: '请填写体重'
	// 		});
	// 		break;
	// 	}
	// }
	savedevices(type) {
		console.log(this.data.inputlist);
		const list = []
		let result = false
		if(type === 2) {
			this.data.inputlist.forEach(item => {
				if (item.value && item.value !== '--' && item.value != 0) {
					const obj = {
						code: item.code,
						checkDate: null,
						level: null,
						value: item.value,
						deviceBrand: '',
						deviceNo: ''
					}
					result = true
					list.push(obj)
				}
			})
		} else {
			const obj = {
				code: this.data.inputlist[0].code,
				checkDate: null,
				level: null,
				value: this.data.inputlist[0].value,
				deviceBrand: '',
				deviceNo: ''
			}
			console.log('2222');
			result = true
			list.push(obj)
		}

		console.log(list);
		if (result == true) {
			this.save(list)
		}
	},
	save(list) {
		let data = {
			name: '体重监测',
			time: formatTime(),
			typecode: 'hxfatmeter',
			typename: '体重监测',
			devices: [
				{
					name: '体重监测',
					kind: 'hxfatmeter',
					items: list
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/wlfatmeter', {
				data
			})
			.then((res) => {
				// console.log(res);
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
				console.log('----保存录入----', res);
				this.gethistrorylist(false)
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	goDetails(e) {
		wx.navigateTo({ url: `/weightManagement/pages/desc/index?examid=${this.data.examid}` });
	},
	openNickname() {
		this.setData({
			editWvalue: '',
			inputshow: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	userNameInput1(e) {
		console.log(e.detail.value, 'userNameInput1userNameInput1');
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[1].value': e.detail.value
		});
	},
	userNameInput3(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[2].value': e.detail.value
		});
	},
	userNameInput4(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[3].value': e.detail.value
		});
	},
	userNameInput5(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[4].value': e.detail.value
		});
	},
	userNameInput6(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[5].value': e.detail.value
		});
	},
	userNameInput7(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[6].value': e.detail.value
		});
	},
	saveNickname() {
		console.log(this.data.inputlist[0].value);

		if (!this.data.inputlist[0].value || this.data.inputlist[0].value == 0 || this.data.inputlist[0].value == 0.0) {
			wx.showToast({
				icon: 'none',
				title: '请填写体重'
			});
			return
		}
		if(Number(this.data.inputlist[0].value) > 200) {
			wx.showToast({
				icon: 'none',
				title: '请输入正确的体重范围'
			});
			return
		}
		this.savedevices(1);

	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
	},
	// 绘制图表
	runColumncCanva() {
		var option = {
			title: {
				// text: '次/分',
				textStyle: {
					fontSize: 9,
					color: '#666666'
				}
			},
			color: ['#37A2DA'],
			legend: {
				data: ['体重变化趋势'],
				icon: 'circle',
				left: 0,
				itemWidth: 10,
				// itemStyle: {
				//     color: '#5BBF70'
				// },
				textStyle: {
				    color: '#333333',
				    fontSize: 20
				}
			},
			grid: {
				left: '0%',
				right: '5%',
				bottom: 0,
				top: '15%',
				containLabel: true,
				show: true
			},

			tooltip: {
				show: true,
				trigger: 'axis'
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: timeArr,
				axisLabel: {
					fontSize: 16,
					rotate: 0 //倾斜度 -90 至 90 默认为0
				}
			},
			yAxis: {
				type: 'value',
				splitLine: {
					lineStyle: {
						type: 'dashed'
					}
				},
				axisLabel: {
					fontSize: 16
				}
			},
			series: seriesDataArr
		};
		//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
		if (chart) {
			chart.setOption(option);
			this.setData({
				show: true
			});
		}
	},
	getEchartData(linedata) {
		seriesDataArr = [
			{
				name: '体重变化趋势',
				type: 'line',
				stack: 'Total',
				smooth: true,
				data: linedata.values
			}
		];
		timeArr = linedata.times;
		this.runColumncCanva();
	},
	doBluetoothAdapterStateChange() {
		console.log('获取蓝牙的状态')
		wx.onBluetoothAdapterStateChange((res) => {
			console.log('蓝牙状态', res)
			if (res.available) {
				this.setData({
					bleStatus: true
				})
				if (!this.data.isInit) {
					this.initPlu()
				}
			} else {
				this.setData({
					bleStatus: false
				})
			}
		})
	},
	// 链接设备
	goBindEq() {
		// this.setData({
		// 	hasSave: false,
		// 	bindDeviceTextInfo: '正在搜索蓝牙设备'
		// })
		// this.setData({
		// 	showDialog: true
		// })
		// this.scanDeviceIC();
		if(!this.data.bleStatus) {
			wx.showToast({
				title: '蓝牙初始化失败,请打开蓝牙',
				icon: 'none',
				duration: 2000
			})
			return
		}
		wx.navigateTo({ url: `/weightManagement/pages/measurement/index?bleStatus=${this.data.bleStatus}` })
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function () { },

	/**
   * 生命周期函数--监听页面显示
   */
	// onShow() { },

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() { },

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		console.log(this.data.bindDevice, '页面卸载')
		if(this.data.bindDevice.deviceId || this.data.bindDevice.macAddr) {
			this.ICDeviceManager.removeDevice(this.data.bindDevice.deviceId ? this.data.bindDevice.deviceId : this.data.bindDevice.macAddr, (macAddr, code) => {
			});
		}
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() { },

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() { },

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() { }
});
